//
//  SurveyerStore.m
//  Surveyer
//
//  Created by Qikun Guo on 13-8-4.
//  Copyright (c) 2013年 Tim. All rights reserved.
//

#import "SurveyerStore.h"
#import "NSManagedObjectModel+KCOrderedAccessorFix.h"

NSString * const SurveyerStoreUpdateNotification = @"SurveyerStoreUpdateNotification";

@implementation SurveyerStore
@synthesize undoManager, allSurvey, app, delegateVC;

+ (SurveyerStore *)defaultStore
{
    static SurveyerStore *defaultStore = nil;
    if (!defaultStore)
    {
        defaultStore = [[super allocWithZone:nil] init];
    }
    return defaultStore;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [self defaultStore];
}

- (id)init
{
    if (self = [super init])
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contentChange:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:nil];
        
        model = [NSManagedObjectModel mergedModelFromBundles:nil];
        NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        
        NSFileManager *fm = [NSFileManager defaultManager];
        NSURL *uContainer = [fm URLForUbiquityContainerIdentifier:nil];
        NSMutableDictionary *options;
        if (uContainer)
            //AppID Problem, reference: http://timroadley.com/2012/04/03/core-data-in-icloud/
            options = [NSMutableDictionary dictionaryWithDictionary:@{@"Surveyer":NSPersistentStoreUbiquitousContentNameKey, uContainer:NSPersistentStoreUbiquitousContentURLKey}];
        else
        {
            options = nil;
        }
        NSURL *storeURL = [NSURL fileURLWithPath:[self itemArchivePath]];
        //maybe could use P565 hotfix?
        NSError *error = nil;
        if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
        {
            [NSException raise:@"Open failed" format:@"Reason: %@", [error localizedDescription]];
        }
        
        context = [[NSManagedObjectContext alloc] init];
        undoManager = [[NSUndoManager alloc] init];
        context.undoManager = undoManager;
        context.persistentStoreCoordinator = psc;
        [model kc_generateOrderedSetAccessors];
        [self load];
    }
    return self;
}

- (NSString *)itemArchivePath
{
    NSArray *documentDirectories =
    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                        NSUserDomainMask, YES);
    
    // Get one and only document directory from that list
    NSString *documentDirectory = [documentDirectories objectAtIndex:0];
    
    return [documentDirectory stringByAppendingPathComponent:@"surveyerStore.data"];
}

- (BOOL)saveChanges
{
    NSError *error = nil;
    BOOL successful = [context save:&error];
    if (!successful)
    {
        NSLog(@"Error saving, %@", [error localizedDescription]);
    }
    return successful;
}

- (void)load
{
    if (!allSurvey)
    {
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        NSEntityDescription *e = [[model entitiesByName] objectForKey:@"Survey"];
        [request setEntity:e];
        /*
        NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"modifiedDate" ascending:NO];
        [request setSortDescriptors:@[sd]];
        */
        NSError *error = nil;
        NSArray *result = [context executeFetchRequest:request error:&error];
        if (!request)
        {
            [NSException raise:@"Fetch failed." format:@"Reason: %@", [error localizedDescription]];
        }
        
        allSurvey = [NSMutableArray arrayWithArray:result];
    }
    
    if (!app)
    {
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        NSEntityDescription *e = [[model entitiesByName] objectForKey:@"App"];
        [request setEntity:e];
        NSError *error = nil;
        NSArray *result = [context executeFetchRequest:request error:&error];
        if (!request)
        {
            [NSException raise:@"Fetch failed." format:@"Reason: %@", [error localizedDescription]];
        }
        if (result.count == 0)
        {
            app = [NSEntityDescription insertNewObjectForEntityForName:@"App" inManagedObjectContext:context];
        }
        else
        {
            app = [result objectAtIndex:0];
        }
    }
}

- (void)sort
{
    NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"modifiedDate" ascending:NO];
    [allSurvey sortUsingDescriptors:@[sd]];
}

- (Survey *)createSurveyWithTitle:(NSString *)title
{
    NSPredicate *p = [NSPredicate predicateWithFormat:@"SELF == '%@'", title];
    if (![allSurvey filteredArrayUsingPredicate:p])
    {
        return nil;
    }
    Survey *s = [NSEntityDescription insertNewObjectForEntityForName:@"Survey" inManagedObjectContext:context];
    NSDate *date = [NSDate date];
    s.modifiedDate =[date timeIntervalSince1970];
    s.title = title;
    s.time = 0;
    [allSurvey addObject:s];
    return s;
}

- (SurveyItem *)createSurveyItemInSurvey:(Survey *)survey
{
    SurveyItem *item = [NSEntityDescription insertNewObjectForEntityForName:@"SurveyItem" inManagedObjectContext:context];
    [survey addItemsObject:item];
    //item.title = NSLocalizedString(@"Untitled", @"default title for SurveyItem");
    item.title = @"";
    item.type = @"Binary";
    item.owner = survey;
    return item;
}

- (Result *)createResultWithSurveyItem:(SurveyItem *)item
{
    Result *result = [NSEntityDescription insertNewObjectForEntityForName:@"Result" inManagedObjectContext:context];
    result.completed = NO;
    result.item = item;
    result.survey = item.owner;
    [item addResultObject:result];
    return result;
}

- (void)removeSurvey:(Survey *)survey
{
    [survey removeItems:survey.items];
    [survey removeResult:survey.result];
    [context deleteObject:survey];
    [allSurvey removeObjectIdenticalTo:survey];
}

- (void)contentChange:(NSNotification *)note
{
    [context mergeChangesFromContextDidSaveNotification:note];
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        NSNotification *updateNote = [NSNotification notificationWithName:SurveyerStoreUpdateNotification object:nil];
        [[NSNotificationCenter defaultCenter] postNotification:updateNote];
    }];
}

- (void)removeUncompletedSurvey
{
    NSMutableArray *toDel = [[NSMutableArray alloc] init];
    for (Survey *s in allSurvey)
    {
        for (Result *r in s.result)
        {
            if (!r.completed)
            {
                [toDel addObject:r];
                
            }
        }
    }
    for (Result *r in toDel)
    {
        [r.survey removeResultObject:r];
        [r.item removeResultObject:r];
    }
    toDel = nil;
}

- (void)shareSurvey:(Survey *)survey ByType:(ShareType)type
{
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
    NSString *TO = survey.textOutput;
    id<ISSContent>publishContent= [ShareSDK content:TO
                                     defaultContent:TO
                                              image:[ShareSDK imageWithPath:imagePath]
                                              title:[survey.title stringByAppendingString:NSLocalizedString(@"Survey Report", @"share to social net. title")]
                                                url:nil
                                        description:TO
                                          mediaType:SSPublishContentMediaTypeText];
    id<ISSContainer> container = [ShareSDK container];
    id<ISSShareOptions> options = [ShareSDK defaultShareOptionsWithTitle:NSLocalizedString(@"Share", nil)
                                                         oneKeyShareList:[NSArray defaultOneKeyShareList] qqButtonHidden:YES wxSessionButtonHidden:YES wxTimelineButtonHidden:NO showKeyboardOnAppear:NO shareViewDelegate:nil friendsViewDelegate:nil picViewerViewDelegate:nil];
    [container setIPadContainerWithView:delegateVC.view arrowDirect:UIPopoverArrowDirectionUp];
    [ShareSDK shareContent:publishContent
                      type:type
               authOptions:nil
              shareOptions:options
             statusBarTips:YES
                    result:^(ShareType type, SSPublishContentState state, id<ISSStatusInfo> statusInfo,id<ICMErrorInfo>error,BOOL end){
                        if (state == SSPublishContentStateSuccess) {
                            NSLog(@"发表成功");
                        }
                        else if (state == SSPublishContentStateFail) {
                            NSLog(@"发布失败!error code == %d, error code == %@",
                                  [error errorCode], [error errorDescription]); }
                    }];
}

- (void)mailSurvey:(Survey *)survey WithDelegate:(UIViewController *)delegate
{
    delegateVC = delegate;
    MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
    mailer.mailComposeDelegate = self;
    [mailer setSubject:[survey.title stringByAppendingString:NSLocalizedString(@" Survey Report", @"share to social net. title")]];
    [mailer setMessageBody:[survey textOutput] isHTML:NO];
    [delegateVC presentViewController:mailer animated:YES completion:nil];
}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [delegateVC dismissViewControllerAnimated:YES completion:nil];
}

- (NSString *)stringToShow
{
    NSString *result = @"Welcome to Surveyer";
    
    //@"NO_LONGER_THAN_THIS:dhjashdjsahdaD";
    return result;
}

- (Survey *)templateSurvey
{
    NSPredicate *p = [NSPredicate predicateWithFormat:@"SELF == '%@'", NSLocalizedString(@"Restaurant", @"The name of the template")];
    if (![allSurvey filteredArrayUsingPredicate:p])
    {
        return nil;
    }
    Survey *s = [NSEntityDescription insertNewObjectForEntityForName:@"Survey" inManagedObjectContext:context];
    s.time = 0;
    s.title = NSLocalizedString(@"Food", @"template title");
    s.intro = NSLocalizedString(@"This is a survey about food", @"template description");
    [allSurvey addObject:s];
    
    SurveyItem *i = [self createSurveyItemInSurvey:s];
    i.title = NSLocalizedString(@"Do you like cooking yourself or going to the restaurant?", nil);
    i.type = @"Binary";
    i.value1 = NSLocalizedString(@"Cooking", nil);
    i.value2 = NSLocalizedString(@"Restaurant", nil);
    
    i = [self createSurveyItemInSurvey:s];
    i.title = NSLocalizedString(@"What's your favorite kind of food?", nil);
    i.type = @"Picker";
    i.value1 = NSLocalizedString(@"Fast food", nil);
    i.value2 = NSLocalizedString(@"Italian food", nil);
    i.value3 = NSLocalizedString(@"French food", nil);
    i.value4 = NSLocalizedString(@"Chinese/Japanese food", nil);
    
    i = [self createSurveyItemInSurvey:s];
    i.title = NSLocalizedString(@"Your favorite restaurant?", nil);
    i.type = @"Text Field";
    i.value1 = NSLocalizedString(@"Please type it in the field below", nil);
    
    i = [self createSurveyItemInSurvey:s];
    i.title = NSLocalizedString(@"From 0-10, please rate your company's cafeteria.", nil);
    i.type = @"Slider";
    i.value1 = @"0";
    i.value2 = @"10";
    return s;
}
@end